package com.store.app.activity;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.store.app.BaseActivity;
import com.store.app.R;
import com.store.app.bean.BitmapBean;
import com.store.app.bean.PosterBean;
import com.store.app.bean.StoresDetailsBean;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.store.app.utils.UtilsBitmap;
import com.yalantis.ucrop.CropUtils;
import com.yalantis.ucrop.UCrop;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/14.
 * 活动页面
 */
public class PostersActivity extends BaseActivity implements IOnHttpListener, View.OnClickListener {

    private ImageView retreat;
    private ImageView poster_one;
    private ImageView poster_two;
    private ImageView poster_three;
    private ImageView poster_four;
    private ImageView poster_five;
    private ImageView imageView;//临时保留你点击的是哪个视图的+
    private Bitmap temBitmap;  //临时存储图片
    private int chooseIndex = 0;
    private int tempIndex = 0;
    private TextView submit;
    private static final int FLAG_CHOOSE_IMG = 5;
    private static final int FLAG_CHOOSE_PHONE = 6;
    private static final int FLAG_MODIFY_FINISH = 7;
    private static final int SHOW_PIC = 8;
    private static String localTempImageFileName = "";
    private List<PosterBean> posterList = new ArrayList<>();      //存放海报信息集合,保存有图片id,图片标题，也是直接提交到服务器 。

    private EditText et1;               //图片描述
    private EditText et2;
    private EditText et3;
    private EditText et4;
    private EditText et5;

    private NetRequest netRequest;

    private BitmapBean bean;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_PIC:
                    Log.v("zyl", "显示图片：" + tempIndex);
                    if (temBitmap == null) {
                        return;
                    }
                    if (tempIndex == 0) {
                        poster_one.setImageBitmap(temBitmap);
                    } else if (tempIndex == 1) {
                        poster_two.setImageBitmap(temBitmap);
                    } else if (tempIndex == 2) {
                        poster_three.setImageBitmap(temBitmap);
                    } else if (tempIndex == 3) {
                        poster_four.setImageBitmap(temBitmap);
                    } else if (tempIndex == 4) {
                        poster_five.setImageBitmap(temBitmap);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_salespromotion_posters);
        Log.v("zyl", "PostersActivity onCreate");
        initView();
        netRequest = new NetRequest(this);
        netRequest.requestQueryStoresInfo(1);
    }

    @Override
    public void onAfinalFail() {
        ToastTools.showShort(PostersActivity.this, "请检查本地网络！");
    }


    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                Gson gson = new Gson();
                StoresDetailsBean storesDetailsBean = gson.fromJson(jsonObject.getJSONObject("detail").toString(), StoresDetailsBean.class);
                Map<String, String> map = Utils.getMapForJson(jsonObject.getJSONObject("doc_url").toString());
                JSONArray jsonArray = new JSONArray(storesDetailsBean.getActivity_pic_info());
                for (int i = 0; i < jsonArray.length(); i++) {
                    String path_id = jsonArray.getJSONObject(i).getString("path_id");
                    String path_url = map.get(path_id);
                    String title = jsonArray.getJSONObject(i).getString("title");
                    Log.v("zyl", "path_url：" + path_url);
                    Log.v("zyl", "title：" + title);
                    posterList.get(i).setPathUrl(path_url);
                    posterList.get(i).setTitle(title);
                    posterList.get(i).setPath_id(path_id);
                }
                refreshUI();
            } catch (Exception e) {

            }
        } else if (requestId == 2) {
            ToastTools.showShort(PostersActivity.this, "提交成功");
            finish();
        } else if (requestId == 3) {
            try {
                JSONObject obj = new JSONObject(result);
                String doc_id = obj.getString("doc_id");
                if (tempIndex == 0&&bean!=null) {
                    posterList.get(0).setPath_id(doc_id);
                    poster_one.setImageBitmap(bean.getBitmap());
                } else if (tempIndex == 1&&bean!=null) {
                    posterList.get(1).setPath_id(doc_id);
                    poster_two.setImageBitmap(bean.getBitmap());
                } else if (tempIndex == 2&&bean!=null) {
                    posterList.get(2).setPath_id(doc_id);
                    poster_three.setImageBitmap(bean.getBitmap());
                } else if (tempIndex == 3&&bean!=null) {
                    posterList.get(3).setPath_id(doc_id);
                    poster_four.setImageBitmap(bean.getBitmap());
                } else if (tempIndex == 4&&bean!=null) {
                    posterList.get(4).setPath_id(doc_id);
                    poster_five.setImageBitmap(bean.getBitmap());
                }
            } catch (Exception e) {
            }
        }
    }

    public void refreshUI() {
        if (!TextUtils.isEmpty(posterList.get(0).getPathUrl())) {
            ImageLoader.getInstance().displayImage(posterList.get(0).getPathUrl(), poster_one);
        }
        if (!TextUtils.isEmpty(posterList.get(1).getPathUrl())) {
            ImageLoader.getInstance().displayImage(posterList.get(1).getPathUrl(), poster_two);
        }
        if (!TextUtils.isEmpty(posterList.get(2).getPathUrl())) {
            ImageLoader.getInstance().displayImage(posterList.get(2).getPathUrl(), poster_three);
        }
        if (!TextUtils.isEmpty(posterList.get(3).getPathUrl())) {
            ImageLoader.getInstance().displayImage(posterList.get(3).getPathUrl(), poster_four);
        }
        if (!TextUtils.isEmpty(posterList.get(4).getPathUrl())) {
            ImageLoader.getInstance().displayImage(posterList.get(4).getPathUrl(), poster_five);
        }
        et1.setText(posterList.get(0).getTitle() + "");
        et2.setText(posterList.get(1).getTitle() + "");
        et3.setText(posterList.get(2).getTitle() + "");
        et4.setText(posterList.get(3).getTitle() + "");
        et5.setText(posterList.get(4).getTitle() + "");
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        ToastTools.showShort(PostersActivity.this, msg);
    }

    private void initView() {
        retreat = (ImageView) findViewById(R.id.retreat);
        poster_one = (ImageView) findViewById(R.id.poster_one);
        poster_two = (ImageView) findViewById(R.id.poster_two);
        poster_three = (ImageView) findViewById(R.id.poster_three);
        poster_four = (ImageView) findViewById(R.id.poster_four);
        poster_five = (ImageView) findViewById(R.id.poster_five);
        submit = (TextView) findViewById(R.id.submit);

        retreat.setOnClickListener(this);
        poster_one.setOnClickListener(this);
        poster_two.setOnClickListener(this);
        poster_three.setOnClickListener(this);
        poster_four.setOnClickListener(this);
        poster_five.setOnClickListener(this);
        submit.setOnClickListener(this);
        et1 = (EditText) findViewById(R.id.et1);
        et2 = (EditText) findViewById(R.id.et2);
        et3 = (EditText) findViewById(R.id.et3);
        et4 = (EditText) findViewById(R.id.et4);
        et5 = (EditText) findViewById(R.id.et5);

        /**
         * 默认创建五个预上传的资源，然后再调用接口时候更新这五个对象
         */
        posterList.add(0, new PosterBean());
        posterList.add(1, new PosterBean());
        posterList.add(2, new PosterBean());
        posterList.add(3, new PosterBean());
        posterList.add(4, new PosterBean());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.retreat:
                finish();
                break;
            //以下是点击五张海报
            case R.id.poster_one:
                chooseIndex = 0;
                imageView = poster_one;
                get_picture();
                break;
            case R.id.poster_two:
                chooseIndex = 1;
                imageView = poster_two;
                get_picture();
                break;
            case R.id.poster_three:
                chooseIndex = 2;
                imageView = poster_three;
                get_picture();
                break;
            case R.id.poster_four:
                chooseIndex = 3;
                imageView = poster_four;
                get_picture();
                break;
            case R.id.poster_five:
                chooseIndex = 4;
                imageView = poster_five;
                get_picture();
                break;
            //提交
            case R.id.submit:
                String title1 = et1.getText().toString().trim();
                String title2 = et2.getText().toString().trim();
                String title3 = et3.getText().toString().trim();
                String title4 = et4.getText().toString().trim();
                String title5 = et5.getText().toString().trim();
                if (!TextUtils.isEmpty(title1)) {
                    if (TextUtils.isEmpty(posterList.get(0).getPath_id())) {
                        ToastTools.showShort(PostersActivity.this, "请先上传图片");
                        return;
                    }
                }

                if (!TextUtils.isEmpty(title2)) {
                    if (TextUtils.isEmpty(posterList.get(1).getPath_id())) {
                        ToastTools.showShort(PostersActivity.this, "请先上传图片");
                        return;
                    }
                }
                if (!TextUtils.isEmpty(title3)) {
                    if (TextUtils.isEmpty(posterList.get(2).getPath_id())) {
                        ToastTools.showShort(PostersActivity.this, "请先上传图片");
                        return;
                    }
                }
                if (!TextUtils.isEmpty(title4)) {
                    if (TextUtils.isEmpty(posterList.get(3).getPath_id())) {
                        ToastTools.showShort(PostersActivity.this, "请先上传图片");
                        return;
                    }
                }
                if (!TextUtils.isEmpty(title5)) {
                    if (TextUtils.isEmpty(posterList.get(4).getPath_id())) {
                        ToastTools.showShort(PostersActivity.this, "请先上传图片");
                        return;
                    }
                }
                if (TextUtils.isEmpty(posterList.get(0).getPath_id()) && TextUtils.isEmpty(posterList.get(1).getPath_id()) && TextUtils.isEmpty(posterList.get(2).getPath_id()) && TextUtils.isEmpty(posterList.get(3).getPath_id()) && TextUtils.isEmpty(posterList.get(4).getPath_id())) {
                    ToastTools.showShort(PostersActivity.this, "请先上传图片");
                    return;
                }


                JSONArray jsonArray = new JSONArray();
                try {
                    JSONObject jsonObjectOne = new JSONObject();
                    JSONObject jsonObjectTwo = new JSONObject();
                    JSONObject jsonObjectThree = new JSONObject();
                    JSONObject jsonObjectFour = new JSONObject();
                    JSONObject jsonObjectFive = new JSONObject();

                    jsonObjectOne.put("path_id", posterList.get(0).getPath_id());
                    jsonObjectOne.put("title", et1.getText().toString().trim() + "");

                    jsonObjectTwo.put("path_id", posterList.get(1).getPath_id());
                    jsonObjectTwo.put("title", et2.getText().toString().trim() + "");

                    jsonObjectThree.put("path_id", posterList.get(2).getPath_id());
                    jsonObjectThree.put("title", et3.getText().toString().trim() + "");

                    jsonObjectFour.put("path_id", posterList.get(3).getPath_id());
                    jsonObjectFour.put("title", et4.getText().toString().trim() + "");

                    jsonObjectFive.put("path_id", posterList.get(4).getPath_id());
                    jsonObjectFive.put("title", et5.getText().toString().trim() + "");
                    jsonArray.put(jsonObjectOne);
                    jsonArray.put(jsonObjectTwo);
                    jsonArray.put(jsonObjectThree);
                    jsonArray.put(jsonObjectFour);
                    jsonArray.put(jsonObjectFive);
                    netRequest.requestStoreUpdatePosters(2, jsonArray);
                } catch (Exception e) {

                }

                break;
        }

    }

    /**
     * 打开系统相册
     */
    public void get_picture() {
        {
            new AlertDialog.Builder(PostersActivity.this)
                    .setTitle("请选择图片来源")
                    .setItems(new String[]{"相册", "相机"},
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    if (which == 0) {
                                        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                        startActivityForResult(intent,
                                                FLAG_CHOOSE_IMG);
                                    } else if (which == 1) {
                                        String status = Environment
                                                .getExternalStorageState();
                                        if (status
                                                .equals(Environment.MEDIA_MOUNTED)) {
                                            try {
                                                localTempImageFileName = "";
                                                localTempImageFileName = String
                                                        .valueOf((new Date())
                                                                .getTime())
                                                        + ".png";
                                                File filePath = SettingData.FILE_PIC_SCREENSHOT;
                                                if (!filePath.exists()) {
                                                    filePath.mkdirs();
                                                }
                                                Intent intent = new Intent(
                                                        MediaStore.ACTION_IMAGE_CAPTURE);
                                                File f = new File(filePath,
                                                        localTempImageFileName);
                                                // localTempImgDir和localTempImageFileName是自己定义的名字
                                                Uri u = Uri.fromFile(f);
                                                intent.putExtra(
                                                        MediaStore.Images.Media.ORIENTATION,
                                                        0);
                                                intent.putExtra(
                                                        MediaStore.EXTRA_OUTPUT,
                                                        u);
                                                startActivityForResult(
                                                        intent,
                                                        FLAG_CHOOSE_PHONE);
                                            } catch (ActivityNotFoundException e) {
                                                //
                                            }
                                        }
                                    }

                                }
                            }).show();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        if (requestCode == FLAG_CHOOSE_IMG && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uriImg = data.getData();
                if (uriImg != null) {
                    Log.d("lxp", uriImg.toString());
                    CropUtils.startCropActivity(uriImg, PostersActivity.this, 16, 5);
                }
            }
        } else if (requestCode == FLAG_CHOOSE_PHONE && resultCode == RESULT_OK) {
            File f = new File(SettingData.FILE_PIC_SCREENSHOT, localTempImageFileName);
            Uri uri = Uri.fromFile(f);
            if (uri != null) {
                Log.d("lxp", uri.toString());
                Log.d("lxp", uri.getPath());
                //压缩图片
                Uri resultUri = UtilsBitmap.getCompressUri(uri);
                Log.d("lxp", "==============" + resultUri);
                CropUtils.startCropActivity(uri, PostersActivity.this, 16, 5);
            }
        } else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
            if (data != null) {
                final Uri resultUri = UCrop.getOutput(data);
                bean = UtilsBitmap.addFilePath3(resultUri.getPath(), this);

                if (bean.getIsBm()!=null){

                    tempIndex  = chooseIndex;//把当前临时位置保存下来，如果不保存，会出现在上传的过程中点击了其他位置而修改了chooseIndex导致错位
                    netRequest.requestUploadPic(3, bean.getIsBm());
                }
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            //剪切失败
            Toast.makeText(PostersActivity.this, "图片剪切失败！", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}
